package com.dhcc.utils.string;

import com.dhcc.utils.Operator;

/**
 * support trim/trimStart/trimEnd
 * @author hibean@qq.com 2017年6月28日
 *
 */
public class TrimOperator implements Operator<String> {

	@Override
	public Object invoke(String operator, String first, Object[] args) {
		if(first==null){
			return null;
		}
		if("trimStart".equals(operator)){
			int len = first.length();
	        int st = 0;
	        while ((st < len) && (first.charAt(st) <= ' ')) {
	            st++;
	        }
	        return ((st > 0)) ? first.substring(st) : first;
		}else if("trimEnd".equals(operator)){
			int len = first.length();
	        char[] val = first.toCharArray();  /* avoid getfield opcode */

	        while ((0 < len) && (val[len - 1] <= ' ')) {
	            len--;
	        }
	        return ((len < first.length())) ? first.substring(0, len) : first;
		}
		return first.trim();
	}

}
